package com.bjsdzk.collector.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;

import com.bjsdzk.collector.entity.response.Result;
import com.bjsdzk.collector.entity.response.ResultCode;
import com.bjsdzk.collector.entity.response.ResultHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import com.alibaba.dubbo.rpc.RpcException;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.Set;
import java.util.function.BinaryOperator;

/**
 * @author sl
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

	
	private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
	 
    @ExceptionHandler(value = {RpcException.class})
    public Result exceptionHandler(Exception e){
        logger.error(e.getMessage(),e);
        return ResultHandler.error(ResultCode.VALIDATION);
    }

    @ExceptionHandler(ValidationException.class)
    public Result handleValidationException(ValidationException e) {
        logger.error(e.getMessage(), e);
        return new Result(ResultCode.VALIDATION.getCode(), e.getCause().getMessage());
    }

    @ExceptionHandler(BindException.class)
    public Result handleValidationException(BindException e) {
        logger.error(e.getMessage(),e);
        String message = e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).reduce("", reduceMessage());
        return ResultHandler.error(ResultCode.VALIDATION.getCode(), message);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public Result  handleConstraintViolationException(ConstraintViolationException e) {
        logger.error(e.getMessage(),e);
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        String message = constraintViolations.stream().map(ConstraintViolation::getMessage).reduce("", reduceMessage()
        );
        return ResultHandler.error(ResultCode.VALIDATION.getCode(), message);
    }
    
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result  handleConstraintViolationException(MethodArgumentNotValidException e) {
        logger.error(e.getMessage(),e);
        String message = e.getBindingResult().getFieldErrors().stream().map(FieldError::getDefaultMessage).reduce("", reduceMessage());
        return new Result(ResultCode.VALIDATION.getCode(), message);
    }

    private BinaryOperator<String> reduceMessage() {
        return (a, b) -> {
            if (StringUtils.isNotEmpty(a)) {
                return String.join(a, "|", b);
            } else {
                return b;
            }
        };
    }
}
